package com.example.controller;

import com.example.entity.Role;
import com.example.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    // 任务二：查询特定角色及其所拥有的所有菜单权限
    @GetMapping("/{roleId}")
    public Map<String, Object> getRoleWithMenusById(@PathVariable Long roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Role role = roleService.findRoleWithMenusById(roleId);
            result.put("success", true);
            result.put("data", role);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 分页查询所有角色 - 修复分页逻辑
    @GetMapping
    public Map<String, Object> getAllRolesWithMenus(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        try {
            Integer offset = (page - 1) * pageSize;  // 添加offset计算
            List<Role> roles = roleService.findAllRolesWithMenus(offset, pageSize);
            Long total = roleService.countAllRoles();

            result.put("success", true);
            result.put("data", roles);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 根据角色名称查询角色
    @GetMapping("/name/{roleName}")
    public Map<String, Object> getRoleByName(@PathVariable String roleName) {
        Map<String, Object> result = new HashMap<>();
        try {
            Role role = roleService.findRoleByName(roleName);
            result.put("success", true);
            result.put("data", role);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    // 任务四：更新角色菜单权限
    @PostMapping("/{roleId}/menus")
    public Map<String, Object> updateRoleMenus(@PathVariable Long roleId, @RequestBody List<Long> menuIds) {
        Map<String, Object> result = new HashMap<>();
        try {
            roleService.updateRoleMenus(roleId, menuIds);
            result.put("success", true);
            result.put("message", "角色权限更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }
}
